from flask import Blueprint, render_template, request, jsonify
from applications.common import curd
from applications.common.utils import validate
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from flask_login import login_required, current_user
from applications.extensions import db
from applications.models import Book, Page, User
from applications.schemas import PageOutSchema

bp = Blueprint('page', __name__, url_prefix='/page')


@bp.get('/')
@authorize("zbook:page:main", log=True)
def main():
    return render_template('zbook/page/main.html')


@bp.get('/data')
@authorize("zbook:page:main", log=True)
def table():
    title = str_escape(request.args.get('title', type=str))
    bookid = str_escape(request.args.get('bookId', type=str))
    print("title:", title, "bookid:", bookid)
    filters = []
    if title:
        filters.append(Page.title.contains(title))
    if bookid:
        filters.append(Page.book_id==int(bookid))
    query = db.session.query(Page)
    query = query.join(Book, Page.book_id == Book.id).with_entities(Page.id, Page.book_id, Page.title, Page.title,
            Page.content, Page.status, Page.sort, Page.uid, Page.update_time, Book.name.label("book_name"))
    pages = query.filter(*filters).order_by(Page.sort).layui_paginate()
    return table_api(data=PageOutSchema(many=True).dump(pages), count=pages.total)



@bp.get('/add')
@authorize("zbook:page:add", log=True)
def add():
    return render_template('zbook/page/add.html')


@bp.post('/save')
# @authorize("zbook:page:add", log=True)
def save():
    req_json = request.get_json(force=True)
    page = Page(
        book_id=str_escape(req_json.get('book_id')),
        title=str_escape(req_json.get('title')),
        img=str_escape(req_json.get('img')),
        content=str_escape(req_json.get('content')),
        status=str_escape(req_json.get('status')),
        uid=1,
        sort=str_escape(req_json.get('sort')),
        changed=0
    )
    r = db.session.add(page)

    db.session.commit()
    return success_api(msg=str(page.id))


@bp.get('/edit/<int:id>')
@authorize("zbook:page:edit", log=True)
def edit(id):
    page = curd.get_one_by_id(Page, id)
    return render_template('zbook/page/edit.html', page=page)



# 启用
@bp.put('/enable')
@authorize("zbook:page:edit", log=True)
def enable():
    id = request.get_json(force=True).get('id')
    if id:
        enable = 1
        d = Page.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="启用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


# 禁用
@bp.put('/disable')
@authorize("zbook:page:edit", log=True)
def dis_enable():
    id = request.get_json(force=True).get('id')
    if id:
        enable = 0
        d = Page.query.filter_by(id=id).update({"status": enable})
        if d:
            db.session.commit()
            return success_api(msg="禁用成功")
        return fail_api(msg="出错啦")
    return fail_api(msg="数据错误")


@bp.put('/update')
@authorize("zbook:page:edit", log=True)
def update():
    json = request.get_json(force=True)
    #id = json.get("deptId"),
    print(json)
    id = str_escape(json.get("id"))
    data = {
        "book_id": validate.str_escape(json.get("bookId")),
        "title": validate.str_escape(json.get("title")),
        "sort": validate.str_escape(json.get("sort")),
        "content": validate.str_escape(json.get("content")),
        "changed": 1
    }
    d = Page.query.filter_by(id=id).update(data)
    book = Book.query.filter(Book.id == data["book_id"]).first()
    if not book.changed:
        book.changed = 1
    else:
        book.changed = book.changed + 1
    db.session.add(book)
    if not d:
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")


@bp.delete('/remove/<int:_id>')
@authorize("zbook:page:remove", log=True)
def remove(_id):
    d = Page.query.filter_by(id=_id).delete()
    db.session.commit()
    if d:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg="删除失败")
